// 用户数据模块
import http from '@/trnall/request/index'
import store from '@/trnall/store'
import tools from '@/trnall/utils/tools'
import wechat from '@/trnall/wechat/wechat'
// import share from '@/trnall/share'

const state = {
	token: uni.getStorageSync("token") || "",
	isLogin: uni.getStorageSync("isLogin") || false, // 是否登陆
	userInfo: uni.getStorageSync("userInfo") || {}, // 用户信息
	shopList: uni.getStorageSync("shopList") || [],
	navBarShopList: uni.getStorageSync("navBarShopList") || [],
	currentShopIndex: uni.getStorageSync("currentShopIndex") || -1,
	selectId: uni.getStorageSync('select_id') || 0,
	// agentInfo: {}, //分销商信息
	// userData: {}, //用户其他相关信息
	// subscribeMessageIdsMap: [], //小程序订阅消息模板ids
	// authType: '' // smsLogin:手机号登录注册, accountLogin:密码登录, forgotPwd:忘记密码, changePwd:修改密码, bindMobile:绑定手机号
}

const getters = {
	token: state => state.token,
	isLogin: state => state.isLogin,
	userInfo: state => state.userInfo,
	shopList: state => state.shopList,
	navBarShopList: state => state.navBarShopList,
	currentShopIndex: state => state.currentShopIndex,
	selectId: state => state.selectId,

	// agentInfo: state => state.agentInfo,
	// userOtherData: state => state.userData,
	// authType: state => state.authType,
	// subscribeMessageIdsMap: state => state.subscribeMessageIdsMap
}

const actions = {
	// 获取用户信息
	getUserInfo({
		commit,
		dispatch,
		getters,
		state
	}, s = false) {
		return new Promise((resolve, reject) => {
			http('user.info').then(res => {
					if (res.code === 1) {
						commit('userInfo', res.data);
						commit('isLogin', true);
						if (s) {
							console.log('sss')
							let shopList = res.data.shop
							if (shopList && shopList?.length > 0) {
								commit('shopList', shopList)
								let temp = [{
									id: 0,
									name: '所有店铺',
									name_text: '所有店铺',
								}];
								let navBarShopList = temp.concat(shopList)
								commit('navBarShopList', navBarShopList)
							}
						}
						resolve(res.data)
					}
				})
				.catch(err => {

				})
		});
		/* return new Promise((resolve, reject) => {
			token && uni.setStorageSync('token', token);
			http('user.info').then(res => {
					console.log('获取用户信息', res)
					if (res.code === 1) {
						let lastLoginStatus = getters.isLogin;
						commit('userInfo', res.data);
						commit('isLogin', true);
						dispatch('showAuthModal', '');
						!lastLoginStatus && share.setShareInfo();
						// 存在分享信息 添加分享记录
						let spm = uni.getStorageSync('spm');
						if (spm) {
							http('common.shareAdd', {
								spm: spm
							});
							uni.removeStorageSync('spm');
						}
						resolve(res.data)
					}

				}).then(() => {
					// 只有在登录的时候请求购物车信息，订单信息，获取登录信息之后。
					// token && dispatch('getCartList');
					token && dispatch('getUserData');
				})
				.catch(e => {
					reject(e)
				})
		}) */
	},
	async getShopList({
		commit,
		getters,
		dispatch
	}, id = 0) {
		return new Promise((resolve, reject) => {
			let requestData = {
				id: id
			};
			http('user.shopList', requestData).then(res => {
					console.log('shopList', requestData, res)
					let temp = [{
						id: 0,
						name: '所有店铺',
						name_text: '所有店铺',
					}];
					if (res.code === 1) {
						let shopList = res.data;
						if (shopList && shopList?.length > 0) {
							commit('shopList', shopList)
							let navBarShopList = temp.concat(shopList)
							commit('navBarShopList', navBarShopList)
							if (requestData.id > 0) commit('currentShopIndex', 0)
							// commit('currentShopIndex', 0)
						} else {
							commit('shopList', [])
							commit('navBarShopList', temp)
							commit('currentShopIndex', 0)
						}
					} else {
						commit('shopList', [])
						commit('navBarShopList', [])
						commit('currentShopIndex', -1)
					}
					resolve(res.data)
				})
				.catch(err => {

				})
		});
	},
	// 自动登录
	async autoLogin({
		commit,
		getters,
		dispatch
	}) {
		if (!getters.isLogin) {
			let userInfo = await wechat.wxMinProgramLogin(true);
			console.log('autoLogin-userInfo', userInfo)
			commit('userInfo', userInfo);
			commit('isLogin', true);
			// commit('shopList', userInfo.shop)
		}
		console.log('autoLogin')
		await dispatch('getUserInfo', true);
	},
	async getUserProfile({
		commit,
		getters,
		dispatch
	}, params) {
		let $vx = this;
		let that = this._vm;
		if (uni.getUserProfile) {
			// return new Promise((resolve, reject) => {
			uni.getUserProfile({ // 必须手动确认触发
				desc: "获取头像昵称", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: res => {
					uni.hideLoading();
					console.log('更新会员资料返回值', res)
					if (res.errMsg === "getUserProfile:ok") {
						that.$util.loading('获取中');
						that.$http('user.updateUserInfo', {
								encryptedData: res.encryptedData,
								iv: res.iv,
								signature: res.signature,
								rawData: res?.rawData,
								nickName: res?.userInfo?.nickName,
								avatarUrl: res?.userInfo?.avatarUrl,
							}).then(res => {
								console.log('更新返回值', res)
								that.requestIng = false
								uni.hideLoading()
								let data = res.data
								if (res.code == 1) {
									that.$util.msg('成功');
									that.$store.dispatch('getUserInfo');
									uni.setStorageSync('authUserInfo', true)
									// resolve(true);
								} else {
									that.$util.msg(res.msg || '更新失败');
									// resolve(false);
								}
								params?.success && params.success(res);
							})
							.catch(err => {
								that.requestIng = false
								uni.hideLoading()
								that.$util.msg('网络异常');
								// resolve(false);
							})
					}
				},
				fail: err => {
					that.requestIng = false
					console.log('getUserProfile-fail')
					uni.setStorageSync('authUserInfo', false)
					uni.hideLoading();
					params?.success && params.success(err);
				}
			});
			// });
		}
	}
	// 用户其他相关信息
	/* getUserData({
		commit
	}) {
		return new Promise((resolve, reject) => {
			http('user.userData').then(res => {
				commit('USER_DATA', res.data);
				resolve(res)
			}).catch(e => {
				reject(e)
			})
		})
	},

	// 获取分销商身份信息
	getAgent({
		commit
	}) {
		return new Promise((resolve, reject) => {
			http('commission.auth').then(res => {
				if (res.code === 1) {
					commit('AGENT_INFO', res.data.data);
				}
				resolve(res)
			}).catch(e => {
				reject(e)
			});
		})
	}, */


	// 登录弹窗控制
	/* showAuthModal({
		commit
	}, type = 'accountLogin') {
		commit('AUTH_TYPE', type);
	}, */

	// 退出登录
	/* logout({
		commit,
		dispatch
	}) {
		uni.getStorageSync('token') && http('user.logout');
		commit('token', "");
		uni.removeStorageSync('chatSessionId');
		commit('isLogin', false);
		commit('userInfo', {});
		commit('CART_LIST', []);
		commit('USER_DATA', {});
		// 重置全局分享信息
		share.setShareInfo();
	}, */

	// 获取订阅消息模板ids;
	/* getMessageIds({
		commit,
		state
	}) {
		http('user.messageIds').then(res => {
			console.log('getMessageIds', res)
			commit('formatMessage', res.data)
			Promise.resolve(res.data)
		}).catch(e => {
			Promise.reject(e)
		})

	}, */
}

const mutations = {
	token(state, payload) {
		state.token = payload;
		uni.setStorageSync("token", payload);
	},
	// 登录态
	isLogin(state, data) {
		state.isLogin = data;
		uni.setStorageSync('isLogin', data);
	},
	// 用户信息
	userInfo(state, data) {
		state.userInfo = data;
		uni.setStorageSync("userInfo", data);
	},
	shopList(state, data) {
		state.shopList = data;
		data.forEach((item, index) => {
			let shopTypeText = '未知';
			if (item.shop_type == 1) {
				shopTypeText = '美团';
			} else if (item.shop_type == 2) {
				shopTypeText = '饿了么';
			} else if (item.shop_type == 3) {
				shopTypeText = '京东';
			}
			data[index]['name_text'] = shopTypeText + '丨' + data[index].name
		})
		// if(state.currentShopIndex == -1) store.commit('currentShopIndex', 0)
		uni.setStorageSync("shopList", data);
	},
	navBarShopList(state, data) {
		state.navBarShopList = data;
		/* data.forEach((item, index) => {
			if (index > 0) {
				data[index].name = (item.shop_type == 1 ? '美团' : '饿了么') + '丨' + data[index].name
			}
		}) */
		uni.setStorageSync("navBarShopList", data);
		if (state.currentShopIndex == -1) store.commit('currentShopIndex', 0)
	},
	currentShopIndex(state, data) {
		console.log('currentShopIndex', data);
		state.currentShopIndex = data;
		uni.setStorageSync("currentShopIndex", data);
		let shopList = state.shopList;
		let selectedShopId = 0;
		if (data > 0) selectedShopId = state.shopList[data - 1]?.id;
		uni.setStorageSync('selectedShopId', selectedShopId);
		store.dispatch('getOrderVerifyNum')
	},
	selectId(state, data) {
		console.log('selectId',data)
		state.selectId = data;
		uni.setStorageSync('select_id', data);
		// if (data > 0) {
		store.dispatch('getShopList');
		// store.commit('currentShopIndex', 0);
		// } else {

		// }
	}
	// 分销商信息
	/* AGENT_INFO(state, data) {
		state.agentInfo = data;
	},
	// 小程序订阅消息模板ids
	MESSAGE_IDS(state, data) {
		state.subscribeMessageIds = data;
	},
	USER_DATA(state, data) {
		state.userData = data;
	},
	AUTH_TYPE(state, data) {
		data ? uni.hideTabBar() : uni.showTabBar();
		state.authType = data;
	},

	// 订阅消息
	subscribeMessage(state, type) {
		let arr = state.subscribeMessageIdsMap[type];
		arr.length && uni.requestSubscribeMessage({
			tmplIds: arr,
			success: (res) => {
				console.log(res);
			},
			fail: (err) => {
				console.log(err);
			}

		});
	},

	// 解析订阅消息数据
	formatMessage(state, messageIdsObj) {
		// 各场景下用到的订阅模板
		let typeMap = {
			'result': ['order_sended'], //支付成功
			'grouponResult': ['groupon_success', 'groupon_fail', 'order_sended'], //拼团支付成功后
			'aftersale': ['refund_agree', 'aftersale_change', 'wallet_change'], //点击售后
			'wallet': ['score_change', 'wallet_apply', 'wallet_change'], //提现提醒
			'store': ['store_order_new'], //门店新订单通知
			'storeApply': ['store_apply'] //门店申请通知
		}
		let idsMap = {}
		Object.keys(typeMap).forEach(key => {
			idsMap[key] = []
			typeMap[key].forEach(item => {
				idsMap[key].push(messageIdsObj[item])
			})
		})
		state.subscribeMessageIdsMap = idsMap
	}, */
}



export default {
	state,
	mutations,
	actions,
	getters
}
